﻿using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.SystemManager;
/*******************************************************************************
 * Copyright © 2016 NFine.Framework 版权所有
 * Author: NFine
 * Description: NFine快速开发平台
 * Website：http://www.nfine.cn
*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;

namespace CubicFWNet.Application.SystemManager
{
    public class UserApp
    {
        private UserRepository service;
        private RoleRepository _roleRepository;
        private RelevanceRepository _relevanceRepository;
        public UserApp()
        {
            service = new UserRepository();
            _roleRepository = new RoleRepository();
            _relevanceRepository = new RelevanceRepository();
        }

        public void Delete(Guid id)
        {
            service.Delete(u => u.Id == id);
            _relevanceRepository.DeleteBy("UserRole", id);
            _relevanceRepository.DeleteBy("UserModule", id);
        }

        public User GetForm(Guid id)
        {
            return service.FindEntity(id);
        }

        public IEnumerable<User> GetList()
        {
            //var expression = ExtLinq.True<User>();
            //if (!string.IsNullOrEmpty(keyword))
            //{
            //    expression = expression.And(t => t.UserName.Contains(keyword));
            //    expression = expression.Or(t => t.FamilyName.Contains(keyword));
            //}
            //expression = expression.And(t => t.UserName != "admin");
            //return service.IQueryable(expression).OrderBy(u => u.SortNo);
            return service.IQueryable(t => t.UserName != "admin").OrderBy(u => u.SortNo);
        }

        public User CheckLogin(string username, string password)
        {
            User user = service.FindEntity(t => t.UserName == username);
            if (user != null)
            {
                if (user.Status)
                {
                    if (PasswordHash.ValidatePassword(password, user.Password))
                    {
                        return user;
                    }
                    else
                    {
                        throw new Exception("用户名或密码错误！");
                    }
                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员");
                }
            }
            else
            {
                throw new Exception("用户名或密码错误！");
            }
        }

        public void AddOrUpdate(User user, string[] moduleIds)
        {
            user.Password = PasswordHash.CreateHash(user.Password);
            if (user.Id == Guid.Empty)
            {
                if (service.IsExist(u => u.UserName == user.UserName))
                {
                    throw new Exception("用户账号已存在");
                }
                user.Id = Guid.NewGuid();
                service.Insert(user);
            }
            else
            {
                service.Update(u => u.Id == user.Id, u => new User { RealName = user.RealName, ShortName = user.ShortName, Memo = user.Memo, Status = user.Status, SortNo = user.SortNo, UserName = user.UserName });
            }
            //更新用户的角色
            //var type = "UserRole";
            //_relevanceRepository.DeleteBy(type, user.Id);
            //var secIds = roleIds.Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => Guid.Parse(a)).ToArray();
            //_relevanceRepository.AddRelevance(type, secIds.ToLookup(u => user.Id));

            //更新用户的模块
            var type = "UserModule";
            _relevanceRepository.DeleteBy(type, user.Id);
            var secIds = moduleIds.Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => Guid.Parse(a)).ToArray();
            _relevanceRepository.AddRelevance(type, secIds.ToLookup(u => user.Id));

        }


        /// <summary>
        /// 加载一个角色全部用户
        /// </summary>
        public IEnumerable<User> Load(Guid roleId, int pageindex, int pagesize)
        {
            if (pageindex < 1) pageindex = 1;  //TODO:如果列表为空新增加一个用户后，前端会传一个0过来，奇怪？？
            IEnumerable<User> users;
            int records = 0;
            if (roleId == Guid.Empty)
            {
                users = service.LoadUsers(pageindex, pagesize);
                records = service.GetCount();
            }
            else
            {
                users = service.LoadInRole(pageindex, pagesize, roleId);
                records = service.GetUserCntInRole(roleId);
            }
            return users;
        }


        /// <summary>
        /// 加载一个用户的全部 角色Ids
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<Guid> LoadRole(Guid userId)
        {
            List<Guid> modules = new List<Guid>();
            if (userId == Guid.Empty)
            {
                return modules;
            }
            return _roleRepository.LoadByUser(userId).ToList();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="oldPwd"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public int UpdatePwd(Guid userID, string oldPwd, string newPwd)
        {
            User u = service.FindEntity(a => a.Id == userID);
            string nPwd = PasswordHash.CreateHash(newPwd);
            if (u != null)
            {
                if (PasswordHash.ValidatePassword(oldPwd, u.Password))
                {
                    u.Password = nPwd;
                    service.Update(u);
                    return 0;
                }
                else
                {
                    return -2; //旧密码错误
                }
            }
            else
            {
                return -1; //用户不存在
            }
        }

        public void UpdatePwdBy(User model)
        {
            service.Update(model);
        }

    }
}
